package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pdstudio.app.Application;
import com.pdstudio.bean.SimpleCity;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.view.SwipeBackActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*
 * 获取城市*/
public class SearchCitysActivity extends SwipeBackActivity {

	public LayoutInflater inflater;
	private View customLiveIndexTitleView;
	private TextView txtTitle;

	private List<SimpleCity> citys;
	private Handler handler;
	public GridView gridview;
	
	private ImageView ivBack;
	private ProgressBar pb;

	final String FOCUSCITYS = "focuscitys";// 存储的key
	SharedPreferences preferences; // 存储用户关注的城市
	SharedPreferences.Editor editor;
	
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_citys_main);
		
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		LinearLayout layout = (LinearLayout) findViewById(R.id.activity_search_citys_main);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));

		
		pb=(ProgressBar)findViewById(R.id.pb_search_city);
		
		ivBack = (ImageView) findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				SearchCitysActivity.this.finish();

			}

		});

		inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		citys = new ArrayList<SimpleCity>();

		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences(FOCUSCITYS, MODE_WORLD_READABLE);
		// 获得修改器
		editor = preferences.edit();

		customLiveIndexTitleView = findViewById(R.id.title_photogallery);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("选择城市");

		gridview = (GridView) findViewById(R.id.photogridview1);

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					if (msg != null && msg.obj != null) {
						try {
							pb.setVisibility(View.GONE);
							citys = (List<SimpleCity>) msg.obj;
							
							Map<String,SimpleCity> temp=new HashMap<String,SimpleCity>();
							if(citys!=null&&citys.size()>0){
								for(int i=0;i<citys.size();i++){
									try{
										temp.put(citys.get(i).cityCode, citys.get(i));
									}catch(Exception e){e.printStackTrace();}
								}
							}
							Application.getInstance().setSimpleCitys(temp);
							
							gridview.setAdapter(new SimpleCityAdapter());
							
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(getApplicationContext(), "服务器数据异常！",
									0).show();
						}
					}
					break;
				}
			}
		};

		InitalData();

	}

	private void InitalData() {
		Thread thread = new Thread() {
			@Override
			public void run() {
				try {
					StationHttpMethod shm = new StationHttpMethod(
							SearchCitysActivity.this);
					List<SimpleCity> cs = shm.GetSimpleCitys(mSpUtil.getAuthCode());
					Message m = handler.obtainMessage(0, cs);
					handler.sendMessage(m);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "网络异常，请稍后重试！", 0)
							.show();
				}
			}
		};
		thread.start();
	}

	public class SimpleCityAdapter extends BaseAdapter {

		private Context context;

		public void SimpleCityAdapter(Context c) {
			this.context = c;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return citys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return citys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			TextView t = new TextView(getApplicationContext());
			t.setTextSize(24);
			//t.setTextAppearance(t.getContext(), R.style.search_city_textview);
			if (citys != null && t != null && citys.get(position) != null) {
				t.setText(citys.get(position).cityName);				
				t.setTag(R.id.tag_citycode, citys.get(position).cityCode);// 1存code
				t.setTag(R.id.tag_cityname, citys.get(position).cityName);// 2存name
				t.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						/*
						String precitys = preferences.getString(FOCUSCITYS, "");// 存储的城市用;分开
						if (precitys != null && precitys.length() > 0
								&& v.getTag(R.id.tag_citycode) != null) {
							if (!precitys.contains((String) v
									.getTag(R.id.tag_citycode))) {
								precitys = precitys + ";"
										+ v.getTag(R.id.tag_citycode);
							}
						} else {
							precitys = v.getTag(R.id.tag_citycode) + "";
						}
						editor.putString(FOCUSCITYS, precitys);
						editor.commit();
						*///20141120废除，使用统一的sharepreference管理
						try{
							Map<String,SimpleCity> nows=Application.getInstance().getSharePreferenceUtil().getFocusCitys();
							if(nows!=null){
								String code=(String)v.getTag(R.id.tag_citycode);
								if(code!=null && !nows.containsKey(code)){
									SimpleCity sc=Application.getInstance().getSimpleCitys().get(code);
									if(sc!=null){
										nows.put(code, sc);
										Application.getInstance().getSharePreferenceUtil().setFocusCitys(nows);
									}
								}
							}
						}catch(Exception e){e.printStackTrace();}
						// 请求代码可以自己设置，这里设置成10 表示
						Intent i = new Intent();
						setResult(10, i);//
						// 关闭掉这个Activity
						finish();
					}
				});
			}
			return t;
		}

	}
}
